﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "排班计划管理";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-form layui-card-header layuiadmin-card-header-auto">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">计划编号</label>
                    <div class="layui-input-block">
                        <input type="text" name="PlanNumber" placeholder="请输入计划编号" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">计划名称</label>
                    <div class="layui-input-block">
                        <input type="text" name="PlanName" placeholder="请输入计划名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">班组类型</label>
                    <div class="layui-input-block">
                        <select name="TeamType" lay-filter="teamType">
                            <option value="">请选择班组类型</option>
                            <option value="注塑">注塑</option>
                            <option value="机加工">机加工</option>
                            <option value="组装">组装</option>
                            <option value="仓库">仓库</option>
                        </select>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">开始日期</label>
                    <div class="layui-input-block">
                        <input type="text" name="StartDate" id="StartDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">结束日期</label>
                    <div class="layui-input-block">
                        <input type="text" name="EndDate" id="EndDate" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn layuiadmin-btn-list" lay-submit lay-filter="LAY-schedulingplan-search">
                        <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i>搜索
                    </button>
                    <button type="reset" class="layui-btn layui-btn-primary layuiadmin-btn-list" id="LAY-schedulingplan-reset">重置</button>
                </div>
            </div>
        </div>

        <div class="layui-card-body">
            <div style="padding-bottom: 10px;">
                <button class="layui-btn layuiadmin-btn-list" data-type="add">添加</button>
                <button class="layui-btn layuiadmin-btn-list layui-btn-danger" data-type="batchdel">批量删除</button>
            </div>
            <table id="LAY-schedulingplan-list" lay-filter="LAY-schedulingplan-list"></table>
            <script type="text/html" id="table-schedulingplan-list">
                {{#  if(d.documentStatus == 0){ }}
                <a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
                <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del"><i class="layui-icon layui-icon-delete"></i>删除</a>
                {{#  } }}
            </script>
            <script type="text/html" id="planNumberTpl">
                <a href="javascript:;" lay-event="view" class="planNumber-view">{{d.planNumber}}</a>
            </script>
        </div>
    </div>
</div>

<script type="text/html" id="schedulingplanForm">
    <form class="layui-form" id="layuiadmin-form-schedulingplan" lay-filter="layuiadmin-form-schedulingplan" style="padding: 20px 30px 0 0;">
        <div class="layui-form-item">
            <label class="layui-form-label">计划编号</label>
            <div class="layui-input-inline">
                <input type="text" name="PlanNumber" id="PlanNumber" lay-verify="required" placeholder="请点击自动生成" autocomplete="off" class="layui-input" readonly>
            </div>
            <div class="layui-input-inline">
                <button type="button" class="layui-btn" id="generatePlanNumber">自动生成</button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">计划名称</label>
            <div class="layui-input-block">
                <input type="text" name="PlanName" lay-verify="required" placeholder="请输入计划名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班组类型</label>
            <div class="layui-input-block">
                <select name="TeamType" lay-filter="teamType" lay-verify="required">
                    <option value="">请选择班组类型</option>
                    <option value="注塑">注塑</option>
                    <option value="机加工">机加工</option>
                    <option value="组装">组装</option>
                    <option value="仓库">仓库</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">开始日期</label>
            <div class="layui-input-block">
                <input type="text" name="StartDate" id="formStartDate" lay-verify="required" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">结束日期</label>
            <div class="layui-input-block">
                <input type="text" name="EndDate" id="formEndDate" lay-verify="required" placeholder="yyyy-MM-dd" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">轮班方式</label>
            <div class="layui-input-block">
                <input type="radio" name="ShiftSystem" value="白班" title="白班" checked lay-filter="shiftSystem">
                <input type="radio" name="ShiftSystem" value="两班倒" title="两班倒" lay-filter="shiftSystem">
                <input type="radio" name="ShiftSystem" value="三班倒" title="三班倒" lay-filter="shiftSystem">
            </div>
        </div>
        <div class="layui-form-item" id="workShiftSystemContainer" style="display: none;">
            <label class="layui-form-label">倒班方式</label>
            <div class="layui-input-block">
                <select name="WorkShiftSystem" lay-filter="workShiftSystem" lay-verify="workShiftRequired">
                    <option value="">请选择倒班方式</option>
                    <option value="按天">按天</option>
                    <option value="按周">按周</option>
                    <option value="按月">按月</option>
                    <option value="按季度">按季度</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item" id="dayCountContainer" style="display: none;">
            <label class="layui-form-label">天数</label>
            <div class="layui-input-inline">
                <input type="number" name="DayCount" id="DayCount" value="" class="layui-input" min="0" lay-verify="dayCountRequired">
            </div>
            <div class="layui-input-inline">
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-sm" id="increaseDayCount"><i class="layui-icon">&#xe654;</i></button>
                    <button type="button" class="layui-btn layui-btn-sm" id="decreaseDayCount"><i class="layui-icon">&#xe67e;</i></button>
                </div>
            </div>
        </div>
        <div class="layui-form-item layui-hide">
            <input type="hidden" name="Id" value="0">
            <input type="hidden" name="DocumentStatus" value="0">
            <button type="submit" lay-submit lay-filter="layuiadmin-form-schedulingplan-submit" id="layuiadmin-form-schedulingplan-submit" class="layui-btn">提交</button>
        </div>
    </form>
    
    <!-- 班次和班组切换面板 -->
                <div class="layui-tab layui-tab-brief" lay-filter="shift-team-tab" id="shiftTeamTab" style="margin-top: 20px; display: none;">
                <ul class="layui-tab-title">
                    <li class="layui-this">班次</li>
                    <li>班组</li>
                </ul>
                <div class="layui-tab-content">
                    <!-- 班次内容 -->
                    <div class="layui-tab-item layui-show">
                        <div class="layui-card">
                            <div class="layui-card-body">
                                <div style="padding-bottom: 10px;">
                                    <button class="layui-btn layui-btn-sm" id="addShift"><i class="layui-icon">&#xe654;</i> 新增</button>
                                    <button class="layui-btn layui-btn-sm layui-btn-normal" id="editShift"><i class="layui-icon">&#xe642;</i> 修改</button>
                                    <button class="layui-btn layui-btn-sm layui-btn-danger" id="deleteShift"><i class="layui-icon">&#xe640;</i> 删除</button>
                                    <span class="layui-badge layui-bg-blue" style="margin-left: 20px; padding: 5px;" id="planIdDisplay">当前排班计划ID: <span id="currentPlanId" style="font-weight:bold;"></span></span>
                                </div>
                        <table class="layui-table" id="shiftTable">
                            <thead>
                                <tr>
                                    <th style="width: 50px;"><input type="checkbox" lay-skin="primary" lay-filter="shift-all"></th>
                                    <th style="width: 60px;">序号</th>
                                    <th style="width: 100px;">班次名称</th>
                                    <th style="width: 100px;">开始时间</th>
                                    <th style="width: 100px;">结束时间</th>
                                    <th style="width: 55px;">备注</th>
                                    <th style="width: 180px;">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- 删除假数据，将通过AJAX加载 -->
                            </tbody>
                        </table>
                        <div id="shiftPagination" style="text-align: right;">
                            <!-- 分页控件，将通过JavaScript动态生成 -->
                        </div>
                    </div>
                </div>
            </div>
            <!-- 班组内容 -->
            <div class="layui-tab-item">
                <div class="layui-card">
                    <div class="layui-card-body">
                        <div style="padding-bottom: 10px;">
                            <button class="layui-btn layui-btn-sm" id="addTeam"><i class="layui-icon">&#xe654;</i> 新增</button>
                            <button class="layui-btn layui-btn-sm layui-btn-normal" id="editTeam"><i class="layui-icon">&#xe642;</i> 修改</button>
                            <button class="layui-btn layui-btn-sm layui-btn-danger" id="deleteTeam"><i class="layui-icon">&#xe640;</i> 删除</button>
                        </div>
                        <table class="layui-table" id="teamTable">
                            <thead>
                                <tr>
                                    <th style="width: 50px;"><input type="checkbox" lay-skin="primary" lay-filter="team-all"></th>
                                    <th style="width: 60px;">序号</th>
                                    <th>班组名称</th>
                                    <th>班组类型</th>
                                    <th>备注</th>
                                    <th style="width: 100px;">操作</th>
                                </tr>
                            </thead>
                            <tbody id="selectedTeamList">
                                <!-- 已选择的班组将在这里显示 -->
                            </tbody>
                        </table>
                        <div id="teamPagination" style="text-align: right;">
                            <div class="layui-box layui-laypage layui-laypage-default">
                                <span class="layui-laypage-count">共 <span id="selectedTeamCount">0</span> 条</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

<!-- 查看详情的表单模板 -->
<script type="text/html" id="schedulingplanViewForm">
    <div class="layui-form" style="padding: 20px 30px 0 0;">
        <div class="layui-form-item">
            <label class="layui-form-label">计划编号</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.planNumber }}</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">计划名称</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.planName }}</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">班组类型</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.teamType }}</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">开始日期</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ layui.util.toDateString(new Date(d.startDate), 'yyyy-MM-dd') }}</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">结束日期</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ layui.util.toDateString(new Date(d.endDate), 'yyyy-MM-dd') }}</div>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">轮班方式</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.shiftSystem }}</div>
            </div>
        </div>
        {{# if(d.shiftSystem === '两班倒' || d.shiftSystem === '三班倒'){ }}
        <div class="layui-form-item">
            <label class="layui-form-label">倒班方式</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.workShiftSystem }}</div>
            </div>
        </div>
        {{# } }}
        <div class="layui-form-item">
            <label class="layui-form-label">单据状态</label>
            <div class="layui-input-block">
                <div class="layui-form-mid">{{ d.documentStatus == 0 ? '草稿' : '已确认' }}</div>
            </div>
        </div>
        
        <!-- 添加班次和班组切换面板 -->
        <div class="layui-tab layui-tab-brief" lay-filter="view-shift-team-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">班次</li>
                <li>班组</li>
            </ul>
            <div class="layui-tab-content">
                <!-- 班次内容 -->
                <div class="layui-tab-item layui-show">
                    <table class="layui-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">序号</th>
                                <th>班次名称</th>
                                <th>开始时间</th>
                                <th>结束时间</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- 班次数据将在JavaScript中动态填充 -->
                        </tbody>
                    </table>
                    <div style="text-align: right;">
                        <div class="layui-box layui-laypage layui-laypage-default">
                            <span class="layui-laypage-count">共 0 条</span>
                            <span class="layui-laypage-limits">
                                <select lay-ignore>
                                    <option value="10" selected>10条/页</option>
                                </select>
                            </span>
                        </div>
                    </div>
                </div>
                
                <!-- 班组内容 -->
                <div class="layui-tab-item">
                    <table class="layui-table">
                        <thead>
                            <tr>
                                <th style="width: 60px;">序号</th>
                                <th>班组名称</th>
                                <th>班组类型</th>
                                <th>备注</th>
                            </tr>
                        </thead>
                        <tbody id="viewTeamList">
                            <!-- 班组数据将在JavaScript中动态填充 -->
                        </tbody>
                    </table>
                    <div id="viewTeamPagination" style="text-align: right;">
                        <div class="layui-box layui-laypage layui-laypage-default">
                            <span class="layui-laypage-count">共 <span id="viewTeamCount">0</span> 条</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

<!-- 班组选择弹窗模板 -->
<script type="text/html" id="teamSelectTpl">
    <div class="layui-fluid" style="padding: 15px;">
        <div class="layui-form">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">班组编号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="teamNumberSearch" placeholder="请输入班组编号" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">班组名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="teamNameSearch" placeholder="请输入班组名称" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline">
                    <button class="layui-btn" id="teamSearchBtn"><i class="layui-icon layui-icon-search"></i> 搜索</button>
                    <button class="layui-btn layui-btn-primary" id="teamResetBtn"><i class="layui-icon layui-icon-refresh"></i> 重置</button>
                </div>
            </div>
        </div>
        
        <table class="layui-table" id="teamSelectTable" lay-filter="teamSelectTable"></table>
        
        <div style="text-align: center; padding-top: 20px;">
            <button class="layui-btn" id="teamSelectConfirm">确定</button>
            <button class="layui-btn layui-btn-primary" id="teamSelectCancel">取消</button>
        </div>
    </div>
</script>

@section Scripts {
    <script>
        layui.use(['table', 'form', 'laydate', 'laytpl', 'element'], function () {
            var $ = layui.$,
                table = layui.table,
                form = layui.form,
                laydate = layui.laydate,
                laytpl = layui.laytpl,
                element = layui.element;

            // 日期选择器
            laydate.render({
                elem: '#StartDate'
            });
            laydate.render({
                elem: '#EndDate'
            });
            laydate.render({
                elem: '#formStartDate'
            });
            laydate.render({
                elem: '#formEndDate'
            });

            // 表格实例
            table.render({
                elem: '#LAY-schedulingplan-list',
                url: '/SchedulingPlan/GetList',
                method: 'post',
                contentType: 'application/json',
                where: {},
                parseData: function (res) {
                    return {
                        "code": res.code,
                        "msg": res.msg,
                        "count": res.count,
                        "data": res.data
                    };
                },
                cols: [[
                    { type: 'checkbox', fixed: 'left' },
                    { field: 'id', width: 80, title: 'ID', sort: true },
                    { field: 'planNumber', width:180, title: '计划编号', templet: '#planNumberTpl' },
                    { field: 'planName', title: '计划名称' },
                    { field: 'teamType', title: '班组类型' },
                    { field: 'startDate', title: '开始日期', templet: function (d) { return layui.util.toDateString(new Date(d.startDate), 'yyyy-MM-dd'); } },
                    { field: 'endDate', title: '结束日期', templet: function (d) { return layui.util.toDateString(new Date(d.endDate), 'yyyy-MM-dd'); } },
                    { field: 'shiftSystem', title: '轮班方式' },
                    { field: 'workShiftSystem', title: '倒班方式' },
                    { field: 'documentStatus', title: '单据状态', templet: function (d) {
                        var status = '';
                        if (d.documentStatus == 0) status = '草稿';
                        else if (d.documentStatus == 1) status = '已确认';
                        return status;
                    } },
                    { title: '操作', width: 150, align: 'center', fixed: 'right', toolbar: '#table-schedulingplan-list' }
                ]],
                page: true,
                limit: 10,
                height: 'full-220',
                text: {
                    none: '暂无相关数据'
                }
            });

            // 监听搜索
            form.on('submit(LAY-schedulingplan-search)', function (data) {
                var field = data.field;
                
                // 执行重载
                table.reload('LAY-schedulingplan-list', {
                    where: field,
                    page: {
                        curr: 1 // 重新从第 1 页开始
                    }
                });
                
                return false;
            });
            
            // 监听重置按钮
            $('#LAY-schedulingplan-reset').on('click', function(){
                // 重置表单
                $('.layui-card-header form')[0].reset();
                // 重新加载表格，不带查询条件
                table.reload('LAY-schedulingplan-list', {
                    where: {},
                    page: {
                        curr: 1
                    }
                });
            });

            // 事件
            var active = {
                add: function () {
                    openFormDialog(0, '添加排班计划');
                },
                batchdel: function () {
                    var checkStatus = table.checkStatus('LAY-schedulingplan-list');
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        return layer.msg('请选择要删除的数据');
                    }
                    
                    // 检查是否存在已确认的单据
                    var hasConfirmed = false;
                    for (var i = 0; i < data.length; i++) {
                        if (data[i].documentStatus == 1) {
                            hasConfirmed = true;
                            break;
                        }
                    }
                    
                    if (hasConfirmed) {
                        return layer.msg('选中的数据中包含已确认的单据，不能删除', {icon: 2});
                    }

                    layer.confirm('确定删除选中的数据吗？', function (index) {
                        var ids = data.map(function (item) {
                            return item.id;
                        });

                        $.ajax({
                            url: '/SchedulingPlan/BatchDelete',
                            type: 'post',
                            contentType: 'application/json',
                            data: JSON.stringify(ids),
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('批量删除成功', {
                                        icon: 1
                                    });
                                    table.reload('LAY-schedulingplan-list');
                                } else {
                                    layer.msg('批量删除失败: ' + res.msg, {
                                        icon: 2
                                    });
                                }
                            },
                            error: function () {
                                layer.msg('服务器错误，请稍后再试', {
                                    icon: 2
                                });
                            }
                        });
                        
                        layer.close(index);
                    });
                }
            };

            $('.layui-btn.layuiadmin-btn-list').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });

            // 监听工具条
            table.on('tool(LAY-schedulingplan-list)', function (obj) {
                var data = obj.data;
                if (obj.event === 'del') {
                    if (data.documentStatus == 1) {
                        layer.msg('已确认的单据不能删除', {icon: 2});
                        return;
                    }
                    
                    layer.confirm('确定删除此排班计划？', function (index) {
                        $.ajax({
                            url: '/SchedulingPlan/Delete?id=' + data.id,
                            type: 'post',
                            success: function (res) {
                                if (res.success) {
                                    layer.msg('删除成功', {
                                        icon: 1
                                    });
                                    obj.del();
                                } else {
                                    layer.msg('删除失败: ' + res.msg, {
                                        icon: 2
                                    });
                                }
                            },
                            error: function () {
                                layer.msg('服务器错误，请稍后再试', {
                                    icon: 2
                                });
                            }
                        });
                        layer.close(index);
                    });
                } else if (obj.event === 'edit') {
                    if (data.documentStatus == 1) {
                        layer.msg('已确认的单据不能编辑', {icon: 2});
                        return;
                    }
                    
                    openFormDialog(data.id, '编辑排班计划', true);
                    // 填充表单数据
                    form.val('layuiadmin-form-schedulingplan', {
                        "Id": data.id,
                        "PlanNumber": data.planNumber,
                        "PlanName": data.planName,
                        "TeamType": data.teamType,
                        "StartDate": layui.util.toDateString(new Date(data.startDate), 'yyyy-MM-dd'),
                        "EndDate": layui.util.toDateString(new Date(data.endDate), 'yyyy-MM-dd'),
                        "ShiftSystem": data.shiftSystem,
                        "WorkShiftSystem": data.workShiftSystem,
                        "DocumentStatus": data.documentStatus.toString()
                    });
                    
                    // 加载排班计划关联的班组
                    loadSchedulingPlanTeams(data.id);

                    // 处理轮班方式联动
                    if (data.shiftSystem === '两班倒' || data.shiftSystem === '三班倒') {
                        $("#workShiftSystemContainer").show();
                        // 如果是按天，则显示天数容器
                        if (data.workShiftSystem === '按天') {
                            $("#dayCountContainer").show();
                        } else {
                            $("#dayCountContainer").hide();
                        }
                    } else {
                        $("#workShiftSystemContainer").hide();
                        $("#dayCountContainer").hide();
                    }
                    
                    // 编辑时禁用自动生成按钮
                    $("#generatePlanNumber").prop("disabled", true).addClass("layui-btn-disabled");
                    
                    // 显示班次和班组切换面板
                    $("#shiftTeamTab").show();
                    
                    form.render(); // 重新渲染表单，确保选择框和单选按钮显示正确
                } else if (obj.event === 'view') {
                    // 查看详情
                    viewSchedulingPlanDetails(data);
                }
            });
            
            // 查看详情方法
            function viewSchedulingPlanDetails(data) {
                // 输出当前查看的排班计划ID，便于调试
                console.log("查看排班计划详情，ID:", data.id);
                
                laytpl($("#schedulingplanViewForm").html()).render(data, function(html){
                    var viewIndex = layer.open({
                        type: 1,
                        title: '查看排班计划详情 (ID:' + data.id + ')',
                        content: html,
                        area: ['700px', '680px'],
                        maxWidth: '100%',
                        btn: ['返回'],
                        yes: function(index) {
                            layer.close(index);
                        },
                        success: function(layero, index) {
                            // 初始化Tab组件
                            element.render('tab', 'view-shift-team-tab');
                            
                            // 加载该排班计划关联的班组
                            loadViewSchedulingPlanTeams(data.id, layero);
                            
                            // 在查看页面也加载该排班计划特定的班次数据
                            loadViewSchedulingPlanShifts(data.id, layero);
                            
                            // Tab切换事件
                            element.on('tab(view-shift-team-tab)', function(data){
                                console.log('查看模式Tab切换到：' + data.index);
                            });
                        }
                    });
                });
            }

            // 自动生成计划编号
            $(document).on('click', '#generatePlanNumber', function () {
                if (!$(this).hasClass("layui-btn-disabled")) {
                    var now = new Date();
                    var year = now.getFullYear();
                    var month = (now.getMonth() + 1).toString().padStart(2, '0');
                    var day = now.getDate().toString().padStart(2, '0');
                    var hours = now.getHours().toString().padStart(2, '0');
                    var minutes = now.getMinutes().toString().padStart(2, '0');
                    var seconds = now.getSeconds().toString().padStart(2, '0');
                    var planNumber = 'PLAN' + year + month + day + hours + minutes + seconds;
                    $("#PlanNumber").val(planNumber);
                }
            });

            // 监听轮班方式变化
            form.on('radio(shiftSystem)', function (data) {
                if (data.value === '两班倒' || data.value === '三班倒') {
                    $("#workShiftSystemContainer").show();
                    
                    // 如果已经选择了倒班方式
                    var workShiftSystem = $('select[name="WorkShiftSystem"]').val();
                    if (workShiftSystem === '按天') {
                        $("#dayCountContainer").show();
                    } else {
                        $("#dayCountContainer").hide();
                    }
                } else {
                    $("#workShiftSystemContainer").hide();
                    $("#dayCountContainer").hide();
                    // 如果是白班，清除工作制和天数
                    $('select[name="WorkShiftSystem"]').val('');
                    $("#DayCount").val('');
                }
                form.render();
            });

            // 监听倒班方式变化
            form.on('select(workShiftSystem)', function (data) {
                if (data.value === '按天') {
                    $("#dayCountContainer").show();
                } else {
                    $("#dayCountContainer").hide();
                    // 非按天模式，清除天数
                    $("#DayCount").val('');
                }
                form.render();
            });

            // 天数加减按钮
            $(document).on('click', '#increaseDayCount', function () {
                var count = parseInt($("#DayCount").val()) || 0;
                $("#DayCount").val(count + 1);
            });

            $(document).on('click', '#decreaseDayCount', function () {
                var count = parseInt($("#DayCount").val()) || 0;
                if (count > 0) {
                    $("#DayCount").val(count - 1);
                }
            });

            // 自定义表单验证规则
            form.verify({
                required: function (value) {
                    if (value.length === 0) {
                        return '必填项不能为空';
                    }
                },
                workShiftRequired: function (value) {
                    // 检查当前轮班方式的值
                    var shiftSystem = $('input[name="ShiftSystem"]:checked').val();
                    if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && value === '') {
                        return '请选择倒班方式';
                    }
                },
                dayCountRequired: function (value) {
                    // 检查当前倒班方式是否为按天
                    var workShiftSystem = $('select[name="WorkShiftSystem"]').val();
                    var shiftSystem = $('input[name="ShiftSystem"]:checked').val();
                    if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && 
                        workShiftSystem === '按天' && 
                        (value === '' || value === null)) {
                        return '请输入天数';
                    }
                }
            });

            // 打开表单对话框
            function openFormDialog(id, title, isEdit) {
                var index = layer.open({
                    type: 1,
                    title: title,
                    content: $('#schedulingplanForm').html(),
                    area: ['700px', '680px'], // 增加高度以适应新增的班次班组面板
                    maxWidth: '100%', // 响应式改进
                    btn: isEdit ? ['确定', '完成', '取消'] : ['确定', '取消'],
                    btn1: function (index, layero) {
                        // 点击确定按钮
                        // 确保表单数据正确
                        var shiftSystem = $('input[name="ShiftSystem"]:checked', layero).val();
                        var workShiftSystem = $('select[name="WorkShiftSystem"]', layero).val();
                        
                        if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && !workShiftSystem) {
                            layer.msg('请选择倒班方式', {icon: 2});
                            return false;
                        }
                        
                        if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && 
                            workShiftSystem === '按天' && 
                            !$('#DayCount', layero).val()) {
                            layer.msg('请输入天数', {icon: 2});
                            return false;
                        }
                        
                        $('input[name="DocumentStatus"]', layero).val('0'); // 确保状态为草稿
                        $('#layuiadmin-form-schedulingplan-submit', layero).click();
                    },
                    btn2: function (index, layero) {
                        if (isEdit) {
                            // 如果是编辑，点击完成按钮
                            // 进行相同的验证
                            var shiftSystem = $('input[name="ShiftSystem"]:checked', layero).val();
                            var workShiftSystem = $('select[name="WorkShiftSystem"]', layero).val();
                            
                            if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && !workShiftSystem) {
                                layer.msg('请选择倒班方式', {icon: 2});
                                return false;
                            }
                            
                            if ((shiftSystem === '两班倒' || shiftSystem === '三班倒') && 
                                workShiftSystem === '按天' && 
                                !$('#DayCount', layero).val()) {
                                layer.msg('请输入天数', {icon: 2});
                                return false;
                            }
                            
                            $('input[name="DocumentStatus"]', layero).val('1'); // 将状态改为已确认
                            $('#layuiadmin-form-schedulingplan-submit', layero).click();
                            return false;
                        } else {
                            // 如果是添加，点击取消按钮
                            layer.close(index);
                        }
                    },
                    btn3: function (index, layero) {
                        // 如果是编辑，点击取消按钮
                        layer.close(index);
                    },
                    success: function(layero, index) {
                        // 清空选中的班组
                        selectedTeams = [];
                        
                        // 打开表单后，重新渲染表单
                        form.render();
                        
                        // 重新渲染日期选择器
                        laydate.render({
                            elem: '#formStartDate'
                        });
                        laydate.render({
                            elem: '#formEndDate'
                        });
                        
                        // 默认隐藏额外选项
                        $("#workShiftSystemContainer", layero).hide();
                        $("#dayCountContainer", layero).hide();
                        
                        // 编辑模式加载数据
                        if (isEdit) {
                            // 显示班次和班组切换面板
                            $("#shiftTeamTab", layero).show();
                            
                            // 初始化tab
                            element.render('tab', 'shift-team-tab');
                            
                            // 获取当前排班计划ID - 确保从表单中获取正确的ID值
                            var currentPlanId = id || $('input[name="Id"]', layero).val();
                            console.log("当前排班计划ID:", currentPlanId);
                            
                            // 显示排班计划ID
                            $("#currentPlanId", layero).text(currentPlanId);
                            
                            // 添加显示文本
                            $("#planIdDisplay", layero).text("当前排班计划ID: " + currentPlanId);
                            
                            // 首次显示时立即加载班次数据，使用当前排班计划ID
                            console.log("初始加载班次，排班计划ID:", currentPlanId);
                            setTimeout(function() {
                                loadClassesList(1, 10, currentPlanId);
                            }, 100);
                            
                            // 监听tab切换
                            element.on('tab(shift-team-tab)', function(data){
                                console.log('Tab切换到：' + data.index);
                                
                                // 当切换到班次标签时，加载班次数据
                                if(data.index === 0) {
                                    // 重新获取当前排班计划ID
                                    var planId = $('input[name="Id"]').val();
                                    loadClassesList(1, 10, planId);
                                }
                            });
                            
                            // 如果是两班倒或三班倒，显示工作制选择
                            var shiftSystem = $('input[name="ShiftSystem"]:checked', layero).val();
                            if (shiftSystem === '两班倒' || shiftSystem === '三班倒') {
                                $("#workShiftSystemContainer", layero).show();
                                
                                // 如果是按天，显示天数输入
                                var workShiftSystem = $('select[name="WorkShiftSystem"]', layero).val();
                                if (workShiftSystem === '按天') {
                                    $("#dayCountContainer", layero).show();
                                }
                            }
                        } else {
                            // 添加模式，设置默认值
                            $('input[name="Id"]', layero).val('0');
                            $('input[name="DocumentStatus"]', layero).val('0');
                            
                            // 生成默认计划编号
                            var now = new Date();
                            var year = now.getFullYear();
                            var month = (now.getMonth() + 1).toString().padStart(2, '0');
                            var day = now.getDate().toString().padStart(2, '0');
                            var hours = now.getHours().toString().padStart(2, '0');
                            var minutes = now.getMinutes().toString().padStart(2, '0');
                            var seconds = now.getSeconds().toString().padStart(2, '0');
                            var planNumber = 'PLAN' + year + month + day + hours + minutes + seconds;
                            $("#PlanNumber", layero).val(planNumber);
                        }
                        
                        // 绑定班次功能按钮
                        bindClassesEvents();
                    }
                });
                
                // 班次相关功能
                
                // 加载班次列表（分页）
                function loadClassesList(pageIndex, pageSize, schedulingPlanId) {
                    // 默认值处理
                    pageIndex = pageIndex || 1;
                    pageSize = pageSize || 10;
                    // 如果没有传入排班计划ID，使用辅助函数获取
                    if (!schedulingPlanId) {
                        schedulingPlanId = getCurrentSchedulingPlanId();
                    }
                    
                    console.log("加载班次数据，排班计划ID:", schedulingPlanId);
                    
                    // 显示加载提示
                    $('#shiftTable tbody').html('<tr><td colspan="7" style="text-align:center;"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 正在加载...</td></tr>');
                    
                    // 在页面显示当前编辑的排班计划ID
                    $('#currentPlanId').text(schedulingPlanId);
                    
                    $.ajax({
                        url: '/Classes/GetList',
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify({
                            PageIndex: pageIndex,
                            PageSize: pageSize,
                            SchedulingPlanId: schedulingPlanId
                        }),
                        success: function(res) {
                            console.log('班次数据返回:', res);
                            if(res.code === 0) {
                                // 记录返回数据，帮助调试
                                console.log("班次数据返回条数:", res.data ? res.data.length : 0);
                                console.log("当前排班计划ID:", schedulingPlanId);
                                
                                var html = '';
                                if(res.data && res.data.length > 0) {
                                    // 检查返回的班次是否都属于当前排班计划
                                    var filteredData = res.data.filter(function(item) {
                                        console.log("编辑模式班次项:", item);
                                        console.log("编辑模式比较:", item.schedulingPlanId, schedulingPlanId);
                                        return item.schedulingPlanId == schedulingPlanId;
                                    });
                                    
                                    console.log("过滤后班次数据条数:", filteredData.length);
                                    
                                    // 使用过滤后的数据
                                    filteredData.forEach(function(item, index) {
                                        html += '<tr>';
                                        html += '<td><input type="checkbox" lay-skin="primary" data-id="' + item.id + '"></td>';
                                        html += '<td>' + item.serialNumber + '</td>';
                                        html += '<td>' + item.classesName + '</td>';
                                        html += '<td>' + formatTime(item.startTime) + '</td>';
                                        html += '<td>' + formatTime(item.endTime) + '</td>';
                                        html += '<td></td>';
                                        html += '<td>';
                                        html += '<a class="layui-btn layui-btn-xs layui-btn-normal edit-class" data-id="' + item.id + '"><i class="layui-icon">&#xe642;</i> 修改</a>';
                                        html += '<a class="layui-btn layui-btn-xs layui-btn-danger del-class" data-id="' + item.id + '"><i class="layui-icon">&#xe640;</i> 删除</a>';
                                        html += '</td>';
                                        html += '</tr>';
                                    });
                                } else {
                                    html = '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
                                }
                                
                                $('#shiftTable tbody').html(html);
                                
                                // 生成分页控件 - 使用过滤后的数据数量
                                var filteredCount = res.data ? res.data.filter(function(item) {
                                    return item.schedulingPlanId == schedulingPlanId;
                                }).length : 0;
                                renderClassesPagination(pageIndex, pageSize, filteredCount);
                                
                                // 重新绑定事件
                                bindClassesEvents();
                                form.render('checkbox');
                            } else {
                                console.error('加载班次数据失败:', res.msg);
                                $('#shiftTable tbody').html('<tr><td colspan="7" style="text-align:center;">加载失败: ' + res.msg + '</td></tr>');
                            }
                        },
                        error: function(xhr, status, error) {
                            console.error('请求班次数据失败:', xhr.responseText);
                            $('#shiftTable tbody').html('<tr><td colspan="7" style="text-align:center;">加载失败，请检查网络连接</td></tr>');
                        }
                    });
                }

                // 渲染班次分页控件
                function renderClassesPagination(pageIndex, pageSize, totalCount) {
                    pageIndex = parseInt(pageIndex);
                    pageSize = parseInt(pageSize);
                    var totalPage = Math.ceil(totalCount / pageSize);
                    
                    var html = '<div class="layui-box layui-laypage layui-laypage-default">';
                    html += '<span class="layui-laypage-count">共 ' + totalCount + ' 条</span>';
                    html += '<span class="layui-laypage-limits">';
                    html += '<select id="classesPageSize" lay-ignore>';
                    [5, 10, 20, 50].forEach(function(size) {
                        html += '<option value="' + size + '"' + (size === pageSize ? ' selected' : '') + '>' + size + '条/页</option>';
                    });
                    html += '</select>';
                    html += '</span>';
                    
                    // 上一页按钮
                    if (pageIndex > 1) {
                        html += '<a href="javascript:;" class="layui-laypage-prev" data-page="' + (pageIndex - 1) + '">';
                        html += '<i class="layui-icon">&lt;</i>';
                        html += '</a>';
                    } else {
                        html += '<a href="javascript:;" class="layui-laypage-prev layui-disabled">';
                        html += '<i class="layui-icon">&lt;</i>';
                        html += '</a>';
                    }
                    
                    // 页码
                    var startPage = Math.max(1, pageIndex - 2);
                    var endPage = Math.min(totalPage, pageIndex + 2);
                    
                    if (startPage > 1) {
                        html += '<a href="javascript:;" class="layui-laypage-first" data-page="1">1</a>';
                        if (startPage > 2) {
                            html += '<span class="layui-laypage-spr">…</span>';
                        }
                    }
                    
                    for (var i = startPage; i <= endPage; i++) {
                        if (i === pageIndex) {
                            html += '<span class="layui-laypage-curr">';
                            html += '<em class="layui-laypage-em"></em>';
                            html += '<em>' + i + '</em>';
                            html += '</span>';
                        } else {
                            html += '<a href="javascript:;" data-page="' + i + '">' + i + '</a>';
                        }
                    }
                    
                    if (endPage < totalPage) {
                        if (endPage < totalPage - 1) {
                            html += '<span class="layui-laypage-spr">…</span>';
                        }
                        html += '<a href="javascript:;" class="layui-laypage-last" data-page="' + totalPage + '">' + totalPage + '</a>';
                    }
                    
                    // 下一页按钮
                    if (pageIndex < totalPage) {
                        html += '<a href="javascript:;" class="layui-laypage-next" data-page="' + (pageIndex + 1) + '">';
                        html += '<i class="layui-icon">&gt;</i>';
                        html += '</a>';
                    } else {
                        html += '<a href="javascript:;" class="layui-laypage-next layui-disabled">';
                        html += '<i class="layui-icon">&gt;</i>';
                        html += '</a>';
                    }
                    
                    // 跳转到页
                    html += '<span class="layui-laypage-skip">';
                    html += '前往 <input type="text" min="1" value="' + pageIndex + '" id="classesJumpPage" class="layui-input"> 页';
                    html += '<button type="button" class="layui-laypage-btn" id="classesJumpButton">GO</button>';
                    html += '</span>';
                    html += '</div>';
                    
                    $('#shiftPagination').html(html);
                    
                    // 绑定分页事件
                    bindClassesPaginationEvents(pageSize);
                }

                // 绑定班次分页事件
                function bindClassesPaginationEvents(pageSize) {
                    // 获取当前排班计划ID
                    var currentSchedulingPlanId = getCurrentSchedulingPlanId();
                    
                    // 页码点击事件
                    $('#shiftPagination a[data-page]').on('click', function() {
                        var page = $(this).data('page');
                        loadClassesList(page, pageSize, currentSchedulingPlanId);
                    });
                    
                    // 每页条数变化事件
                    $('#classesPageSize').on('change', function() {
                        var newPageSize = parseInt($(this).val());
                        loadClassesList(1, newPageSize, currentSchedulingPlanId);
                    });
                    
                    // 跳转页事件
                    $('#classesJumpButton').on('click', function() {
                        var page = parseInt($('#classesJumpPage').val());
                        if (isNaN(page) || page < 1) {
                            page = 1;
                        }
                        loadClassesList(page, pageSize, currentSchedulingPlanId);
                    });
                    
                    // 回车键跳转
                    $('#classesJumpPage').on('keypress', function(e) {
                        if (e.which === 13) { // Enter键
                            var page = parseInt($(this).val());
                            if (isNaN(page) || page < 1) {
                                page = 1;
                            }
                            loadClassesList(page, pageSize, currentSchedulingPlanId);
                        }
                    });
                }

                // 格式化时间函数
                function formatTime(timeStr) {
                    if (!timeStr) return '';
                    var date = new Date(timeStr);
                    var hours = date.getHours().toString().padStart(2, '0');
                    var minutes = date.getMinutes().toString().padStart(2, '0');
                    return hours + ':' + minutes;
                }

                // 打开班次编辑弹窗
                function openClassesForm(id, title, isEdit) {
                    // 获取当前编辑的排班计划ID
                    var currentSchedulingPlanId = $('input[name="Id"]').val() || 0;
                    
                    // 显示当前排班计划ID，便于调试
                    console.log("当前操作的排班计划ID:", currentSchedulingPlanId);
                    
                    // 不再阻止用户添加班次
                    // if (!currentSchedulingPlanId || currentSchedulingPlanId == 0) {
                    //     layer.msg('请先保存排班计划，再添加班次', {icon: 2});
                    //     return;
                    // }
                    
                    var formHtml = '<form class="layui-form" id="classesForm" lay-filter="classesForm" style="padding: 20px;">' +
                        '<div class="layui-form-item">' +
                        '    <label class="layui-form-label">序号</label>' +
                        '    <div class="layui-input-block">' +
                        '        <input type="number" name="SerialNumber" lay-verify="required" placeholder="请输入序号" autocomplete="off" class="layui-input">' +
                        '    </div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '    <label class="layui-form-label">班次名称</label>' +
                        '    <div class="layui-input-block">' +
                        '        <input type="text" name="ClassesName" lay-verify="required" placeholder="请输入班次名称" autocomplete="off" class="layui-input">' +
                        '    </div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '    <label class="layui-form-label">开始时间</label>' +
                        '    <div class="layui-input-block">' +
                        '        <input type="text" name="StartTime" id="startTime" lay-verify="required" placeholder="请选择开始时间" autocomplete="off" class="layui-input">' +
                        '    </div>' +
                        '</div>' +
                        '<div class="layui-form-item">' +
                        '    <label class="layui-form-label">结束时间</label>' +
                        '    <div class="layui-input-block">' +
                        '        <input type="text" name="EndTime" id="endTime" lay-verify="required" placeholder="请选择结束时间" autocomplete="off" class="layui-input">' +
                        '    </div>' +
                        '</div>' +
                        '<div class="layui-form-item" style="display:none;">' +
                        '    <input type="hidden" name="Id" value="' + (id || 0) + '">' +
                        '    <input type="hidden" name="SchedulingPlanId" value="' + currentSchedulingPlanId + '">' +
                        '    <button type="submit" lay-submit lay-filter="classes-form-submit" id="classes-form-submit" class="layui-btn">提交</button>' +
                        '</div>' +
                        '</form>';

                    // 使用全局变量存储当前班次弹窗索引，以便在任何地方都能访问
                    window.currentClassesFormIndex = layer.open({
                        type: 1,
                        title: title,
                        content: formHtml,
                        area: ['500px', '350px'],
                        btn: ['确定', '取消'],
                        yes: function(index, layero) {
                            $('#classes-form-submit').click();
                        },
                        success: function(layero) {
                            form.render();
                            
                            // 时间选择器
                            laydate.render({
                                elem: '#startTime',
                                type: 'time',
                                format: 'HH:mm'
                            });
                            laydate.render({
                                elem: '#endTime',
                                type: 'time',
                                format: 'HH:mm'
                            });
                            
                            if(isEdit && id) {
                                // 加载班次数据
                                loadClassesData(id, layero);
                            }
                            
                            // 监听表单提交
                            form.on('submit(classes-form-submit)', function(data) {
                                var field = data.field;
                                console.log('提交的表单数据:', field);
                                
                                if (!field.SerialNumber) {
                                    layer.msg('请输入序号', {icon: 2});
                                    return false;
                                }
                                
                                if (!field.ClassesName) {
                                    layer.msg('请输入班次名称', {icon: 2});
                                    return false;
                                }
                                
                                if (!field.StartTime) {
                                    layer.msg('请选择开始时间', {icon: 2});
                                    return false;
                                }
                                
                                if (!field.EndTime) {
                                    layer.msg('请选择结束时间', {icon: 2});
                                    return false;
                                }
                                
                                // 确保SerialNumber是数字
                                var serialNumber = parseInt(field.SerialNumber);
                                if (isNaN(serialNumber)) {
                                    layer.msg('序号必须是数字', {icon: 2});
                                    return false;
                                }
                                
                                // 处理时间格式
                                var now = new Date();
                                var dateString = now.getFullYear() + '-' + 
                                                (now.getMonth() + 1).toString().padStart(2, '0') + '-' + 
                                                now.getDate().toString().padStart(2, '0');
                                
                                var startTimeStr = dateString + 'T' + field.StartTime + ':00';
                                var endTimeStr = dateString + 'T' + field.EndTime + ':00';
                                
                                console.log('开始时间字符串:', startTimeStr);
                                console.log('结束时间字符串:', endTimeStr);
                                
                                // 提交数据
                                var url = isEdit ? '/Classes/Update?id=' + field.Id : '/Classes/CreateClasses';
                                
                                // 简化处理，确保SerialNumber是整数
                                var data = {
                                    SerialNumber: parseInt(field.SerialNumber),
                                    ClassesName: field.ClassesName,
                                    StartTime: field.StartTime, // 直接使用HH:mm格式
                                    EndTime: field.EndTime      // 直接使用HH:mm格式
                                };
                                
                                console.log('发送的数据:', data);
                                
                                // 显示加载中
                                var loadIndex = layer.load(1, {
                                    shade: [0.3, '#000']
                                });
                                // 获取当前编辑的排班计划ID
                                var schedulingPlanId = $('input[name="SchedulingPlanId"]').val() || getCurrentSchedulingPlanId();
                                
                                // 如果仍然是0，弹出对话框让用户手动输入ID
                                if (!schedulingPlanId || schedulingPlanId == 0) {
                                    layer.close(loadIndex); // 先关闭加载中
                                    layer.prompt({
                                        formType: 0,
                                        value: '',
                                        title: '请输入排班计划ID',
                                        area: ['200px', '100px']
                                    }, function(value, index, elem){
                                        if (value && !isNaN(value)) {
                                            schedulingPlanId = value;
                                            layer.close(index);
                                            // 重新显示加载中
                                            loadIndex = layer.load(1, {
                                                shade: [0.3, '#000']
                                            });
                                            // 继续提交数据
                                            continueSubmit();
                                        } else {
                                            layer.msg('请输入有效的排班计划ID（数字）', {icon: 2});
                                        }
                                    });
                                } else {
                                    // 直接继续提交
                                    continueSubmit();
                                }
                                
                                // 提交数据的函数
                                function continueSubmit() {
                                
                                    // 添加排班计划ID到数据中
                                    data.SchedulingPlanId = schedulingPlanId;
                                    
                                    console.log("班次提交的数据", data);
                                    
                                    $.ajax({
                                        url: url,
                                        type: 'post',
                                        contentType: 'application/json',
                                        data: JSON.stringify(data),
                                        success: function(res) {
                                            layer.close(loadIndex);
                                            console.log('班次保存响应:', res);
                                            if(res.success) {
                                                // 使用全局变量关闭班次对话框
                                                layer.close(window.currentClassesFormIndex);
                                                layer.msg(isEdit ? '修改成功' : '添加成功', {icon: 1});
                                                // 重新加载当前排班计划的班次列表
                                                loadClassesList(1, 10, schedulingPlanId);
                                            } else {
                                                layer.msg((isEdit ? '修改' : '添加') + '失败: ' + (res.msg || '未知错误'), {icon: 2});
                                            }
                                        },
                                        error: function(xhr, status, error) {
                                            layer.close(loadIndex);
                                            console.error('班次保存错误:', xhr.responseText);
                                            var errorMsg = '服务器错误，请稍后再试';
                                            try {
                                                var errorResponse = JSON.parse(xhr.responseText);
                                                if(errorResponse && errorResponse.error && errorResponse.error.message) {
                                                    errorMsg = errorResponse.error.message;
                                                }
                                            } catch(e) {}
                                            
                                            layer.msg((isEdit ? '修改' : '添加') + '失败: ' + errorMsg, {icon: 2});
                                        }
                                    });
                                }
                                
                                return false;
                            });
                        }
                    });
                }

                // 加载班次数据
                function loadClassesData(id, layero) {
                    $.ajax({
                        url: '/Classes/Get',
                        type: 'get',
                        data: { id: id },
                        success: function(res) {
                            if(res.success && res.data) {
                                var data = res.data;
                                var startTime = new Date(data.startTime);
                                var endTime = new Date(data.endTime);
                                
                                form.val('classesForm', {
                                    "Id": data.id,
                                    "SerialNumber": data.serialNumber,
                                    "ClassesName": data.classesName,
                                    "StartTime": startTime.getHours().toString().padStart(2, '0') + ':' + startTime.getMinutes().toString().padStart(2, '0'),
                                    "EndTime": endTime.getHours().toString().padStart(2, '0') + ':' + endTime.getMinutes().toString().padStart(2, '0')
                                });
                            } else {
                                layer.msg('加载班次数据失败', {icon: 2});
                                layer.close(layer.index);
                            }
                        },
                        error: function() {
                            layer.msg('服务器错误，请稍后再试', {icon: 2});
                            layer.close(layer.index);
                        }
                    });
                }
                
                // 绑定班次相关按钮事件
                function bindClassesEvents() {
                    // 添加班次按钮
                    $('#addShift').off('click').on('click', function() {
                        openClassesForm(0, '新增班次', false);
                    });
                    
                    // 修改班次按钮（批量操作中的按钮）
                    $('#editShift').off('click').on('click', function() {
                        var checkedBoxes = $('#shiftTable tbody input[type="checkbox"]:checked');
                        if(checkedBoxes.length !== 1) {
                            layer.msg('请选择一个班次进行修改', {icon: 0});
                            return;
                        }
                        var id = checkedBoxes.eq(0).data('id');
                        openClassesForm(id, '修改班次', true);
                    });
                    
                    // 删除班次按钮（批量操作中的按钮）
                    $('#deleteShift').off('click').on('click', function() {
                        var checkedBoxes = $('#shiftTable tbody input[type="checkbox"]:checked');
                        if(checkedBoxes.length === 0) {
                            layer.msg('请选择要删除的班次', {icon: 0});
                            return;
                        }
                        
                        layer.confirm('确定删除选中的班次吗？', function(index) {
                            var ids = [];
                            checkedBoxes.each(function() {
                                ids.push($(this).data('id'));
                            });
                            
                            $.ajax({
                                url: '/Classes/BatchDelete',
                                type: 'post',
                                contentType: 'application/json',
                                data: JSON.stringify(ids),
                                success: function(res) {
                                                                                if(res.success) {
                                                layer.msg('批量删除成功', {icon: 1});
                                                // 获取当前排班计划ID
                                                var currentPlanId = $('input[name="Id"]').val() || 0;
                                                loadClassesList(1, 10, currentPlanId); // 重新加载班次列表
                                    } else {
                                        layer.msg('批量删除失败: ' + (res.msg || '未知错误'), {icon: 2});
                                    }
                                    layer.close(index);
                                },
                                error: function() {
                                    layer.msg('服务器错误，请稍后再试', {icon: 2});
                                    layer.close(index);
                                }
                            });
                        });
                    });
                    
                    // 修改班次（行内按钮）
                    $('.edit-class').off('click').on('click', function() {
                        var id = $(this).data('id');
                        openClassesForm(id, '修改班次', true);
                    });
                    
                    // 删除班次（行内按钮）
                    $('.del-class').off('click').on('click', function() {
                        var id = $(this).data('id');
                        layer.confirm('确定删除该班次吗？', function(index) {
                            $.ajax({
                                url: '/Classes/Delete?id=' + id,
                                type: 'post',
                                success: function(res) {
                                                                                if(res.success) {
                                                layer.msg('删除成功', {icon: 1});
                                                // 获取当前排班计划ID
                                                var currentPlanId = $('input[name="Id"]').val() || 0;
                                                loadClassesList(1, 10, currentPlanId); // 重新加载班次列表
                                    } else {
                                        layer.msg('删除失败: ' + (res.msg || '未知错误'), {icon: 2});
                                    }
                                    layer.close(index);
                                },
                                error: function() {
                                    layer.msg('服务器错误，请稍后再试', {icon: 2});
                                    layer.close(index);
                                }
                            });
                        });
                    });
                }

                // 监听表单提交
                form.on('submit(layuiadmin-form-schedulingplan-submit)', function (data) {
                    var field = data.field;
                    var url = field.Id == 0 ? '/SchedulingPlan/Create' : '/SchedulingPlan/Update?id=' + field.Id;
                    
                    // 日期格式转换
                    if (field.StartDate) {
                        field.StartDate = formatDate(field.StartDate);
                    }
                    if (field.EndDate) {
                        field.EndDate = formatDate(field.EndDate);
                    }
                    
                    // 确保DayCount字段正确
                    if (field.ShiftSystem === '两班倒' || field.ShiftSystem === '三班倒') {
                        if (field.WorkShiftSystem === '按天' && field.DayCount) {
                            field.DayCount = parseInt(field.DayCount) || 0;
                        } else {
                            // 非"按天"模式下，无需天数值
                            field.DayCount = 0;
                        }
                    } else {
                        // 白班模式下，无需天数值
                        field.DayCount = 0;
                        // 如果是白班，清除工作制
                        field.WorkShiftSystem = "";
                    }
                    
                    // 添加班组数据
                    field.TeamIds = selectedTeams.map(function(item) {
                        return item.id;
                    });
                    
                    // 确保字段类型正确
                    field.DocumentStatus = parseInt(field.DocumentStatus) || 0;
                    
                    // 将ID转为整数
                    if (field.Id && field.Id != 0) {
                        field.Id = parseInt(field.Id);
                    }
                    
                    console.log("提交的表单数据:", field);
                    
                    // 提交数据
                    $.ajax({
                        url: url,
                        type: 'post',
                        contentType: 'application/json',
                        data: JSON.stringify(field),
                        success: function (res) {
                            if (res.success) {
                                layer.close(index);
                                var message = '';
                                if (field.Id == 0) {
                                    message = '添加成功';
                                } else {
                                    message = field.DocumentStatus == '1' ? '单据已完成' : '修改成功';
                                }
                                layer.msg(message, {
                                    icon: 1
                                });
                                table.reload('LAY-schedulingplan-list');
                            } else {
                                layer.msg(field.Id == 0 ? '添加失败: ' : '修改失败: ' + res.msg, {
                                    icon: 2
                                });
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('请求错误:', xhr.responseText);
                            var errorMsg = '服务器错误，请稍后再试';
                            try {
                                var errorData = JSON.parse(xhr.responseText);
                                if (errorData && errorData.error && errorData.error.message) {
                                    errorMsg = errorData.error.message;
                                }
                            } catch (e) {}
                            
                            layer.msg(errorMsg, {
                                icon: 2
                            });
                        }
                    });
                    
                    return false;
                });
            }
            
            // 日期格式转换函数
            function formatDate(dateStr) {
                if (!dateStr) return '';
                var date = new Date(dateStr);
                if (isNaN(date.getTime())) {
                    // 尝试其他格式解析
                    var parts = dateStr.split('-');
                    if (parts.length === 3) {
                        date = new Date(parts[0], parts[1] - 1, parts[2]);
                    }
                }
                return date.toISOString();
            }

            // 已选择的班组数组
            var selectedTeams = [];
            
            // 监听班组添加按钮
            $(document).on('click', '#addTeam', function() {
                openTeamSelectDialog();
            });
            
            // 打开班组选择弹窗
            function openTeamSelectDialog() {
                layer.open({
                    type: 1,
                    title: '班组选择',
                    content: $('#teamSelectTpl').html(),
                    area: ['800px', '550px'],
                    success: function(layero, index) {
                        // 初始化班组选择表格
                        renderTeamSelectTable(layero);
                        
                        // 监听搜索按钮
                        $('#teamSearchBtn', layero).on('click', function() {
                            var teamNumber = $('input[name="teamNumberSearch"]', layero).val();
                            var teamName = $('input[name="teamNameSearch"]', layero).val();
                            
                            // 重载表格
                            table.reload('teamSelectTable', {
                                where: {
                                    skipCount: 0,
                                    maxResultCount: 100,
                                    teamNumber: teamNumber,
                                    teamName: teamName,
                                    teamType: ''
                                }
                            });
                        });
                        
                        // 监听重置按钮
                        $('#teamResetBtn', layero).on('click', function() {
                            $('input[name="teamNumberSearch"]', layero).val('');
                            $('input[name="teamNameSearch"]', layero).val('');
                            
                            // 重载表格
                            table.reload('teamSelectTable', {
                                where: {
                                    skipCount: 0,
                                    maxResultCount: 100,
                                    teamNumber: '',
                                    teamName: '',
                                    teamType: ''
                                }
                            });
                        });
                        
                        // 监听确定按钮
                        $('#teamSelectConfirm', layero).on('click', function() {
                            // 获取选中的数据
                            var checkStatus = table.checkStatus('teamSelectTable');
                            var data = checkStatus.data;
                            
                            console.log('选中的班组数据:', data);
                            console.log('选中数量:', data.length);
                            
                            if(data.length === 0) {
                                layer.msg('请选择班组', {icon: 0});
                                return;
                            }
                            
                            // 将选中的班组添加到已选择列表中（避免重复）
                            data.forEach(function(item) {
                                var exists = selectedTeams.some(function(team) {
                                    return team.id === item.id;
                                });
                                
                                if(!exists) {
                                    selectedTeams.push(item);
                                }
                            });
                            
                            console.log('更新后的已选择班组:', selectedTeams);
                            
                            // 重新渲染已选择的班组列表
                            renderSelectedTeams();
                            
                            // 关闭弹窗
                            layer.close(index);
                        });
                        
                        // 监听取消按钮
                        $('#teamSelectCancel', layero).on('click', function() {
                            layer.close(index);
                        });
                    }
                });
            }
            
            // 渲染班组选择表格
            function renderTeamSelectTable(layero) {
                table.render({
                    elem: '#teamSelectTable',
                    url: '/Team/GetAllTeams',
                    method: 'get',
                    where: {
                        skipCount: 0,
                        maxResultCount: 100,
                        teamNumber: '',
                        teamName: '',
                        teamType: ''
                    },
                    parseData: function(res) {
                        console.log('服务器返回数据:', res);
                        return {
                            "code": res.code,
                            "msg": res.msg,
                            "count": res.count,
                            "data": res.data
                        };
                    },
                    cols: [[
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: '序号', width: 60, sort: true},
                        {field: 'teamNumber', title: '班组编号', width: 150},
                        {field: 'teamName', title: '班组名称', width: 150},
                        {field: 'teamType', title: '班组类型', width: 100},
                        {field: 'descr', title: '备注'}
                    ]],
                    page: true,
                    limit: 100,
                    limits: [10, 20, 50, 100],
                    height: 400,
                    text: {
                        none: '暂无相关数据'
                    }
                });
                
                // 监听搜索按钮
                $('#teamSearchBtn', layero).on('click', function() {
                    var teamNumber = $('input[name="teamNumberSearch"]', layero).val();
                    var teamName = $('input[name="teamNameSearch"]', layero).val();
                    
                    // 重载表格
                    table.reload('teamSelectTable', {
                        where: {
                            skipCount: 0,
                            maxResultCount: 100,
                            teamNumber: teamNumber,
                            teamName: teamName,
                            teamType: ''
                        }
                    });
                });
                
                // 监听重置按钮
                $('#teamResetBtn', layero).on('click', function() {
                    $('input[name="teamNumberSearch"]', layero).val('');
                    $('input[name="teamNameSearch"]', layero).val('');
                    
                    // 重载表格
                    table.reload('teamSelectTable', {
                        where: {
                            skipCount: 0,
                            maxResultCount: 100,
                            teamNumber: '',
                            teamName: '',
                            teamType: ''
                        }
                    });
                });
            }
            
            // 渲染已选择的班组列表
            function renderSelectedTeams() {
                var html = '';
                
                console.log('渲染已选择班组，数量:', selectedTeams.length);
                console.log('已选择班组数据:', selectedTeams);
                
                selectedTeams.forEach(function(item, index) {
                    html += '<tr>';
                    html += '<td><input type="checkbox" lay-skin="primary" data-id="' + item.id + '"></td>';
                    html += '<td>' + (index + 1) + '</td>';
                    html += '<td>' + item.teamName + '</td>';
                    html += '<td>' + item.teamType + '</td>';
                    html += '<td>' + (item.descr || '') + '</td>';
                    html += '<td><a class="layui-btn layui-btn-xs layui-btn-danger" data-id="' + item.id + '">删除</a></td>';
                    html += '</tr>';
                });
                
                $('#selectedTeamList').html(html);
                $('#selectedTeamCount').text(selectedTeams.length);
                
                // 重新渲染复选框
                form.render('checkbox');
                
                // 绑定删除事件
                $('#selectedTeamList .layui-btn-danger').on('click', function() {
                    var id = $(this).data('id');
                    removeSelectedTeam(id);
                });
            }
            
            // 移除已选择的班组
            function removeSelectedTeam(id) {
                selectedTeams = selectedTeams.filter(function(item) {
                    return item.id !== id;
                });
                
                renderSelectedTeams();
            }
            
            // 监听删除按钮
            $(document).on('click', '#deleteTeam', function() {
                var checkedBoxes = $('#selectedTeamList input[type="checkbox"]:checked');
                
                if(checkedBoxes.length === 0) {
                    layer.msg('请选择要删除的班组', {icon: 0});
                    return;
                }
                
                layer.confirm('确定删除选中的班组吗？', function(index) {
                    checkedBoxes.each(function() {
                        var id = $(this).data('id');
                        removeSelectedTeam(id);
                    });
                    
                    layer.close(index);
                });
            });

            // 加载排班计划关联的班组
            function loadSchedulingPlanTeams(schedulingPlanId) {
                // 清空当前选择的班组
                selectedTeams = [];
                
                $.ajax({
                    url: '/SchedulingPlan/GetTeams',
                    type: 'get',
                    data: { id: schedulingPlanId },
                    success: function(res) {
                        console.log('加载班组数据返回:', res);
                        if (res.code === 0 && Array.isArray(res.data)) {
                            selectedTeams = res.data;
                            console.log('加载到的班组数据:', selectedTeams);
                            renderSelectedTeams();
                        }
                    },
                    error: function(err) {
                        console.error('加载班组数据失败:', err);
                        layer.msg('加载班组数据失败', {icon: 2});
                    }
                });
            }

            // 加载排班计划关联的班组到查看页面
            function loadViewSchedulingPlanTeams(schedulingPlanId, layero) {
                $.ajax({
                    url: '/SchedulingPlan/GetTeams',
                    type: 'get',
                    data: { id: schedulingPlanId },
                    success: function(res) {
                        if (res.code === 0 && Array.isArray(res.data)) {
                            var teams = res.data;
                            var html = '';
                            
                            teams.forEach(function(team, index) {
                                html += '<tr>';
                                html += '<td>' + (index + 1) + '</td>';
                                html += '<td>' + team.teamName + '</td>';
                                html += '<td>' + team.teamType + '</td>';
                                html += '<td>' + (team.descr || '') + '</td>';
                                html += '</tr>';
                            });
                            
                            if (html === '') {
                                html = '<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>';
                            }
                            
                            $('#viewTeamList', layero).html(html);
                            $('#viewTeamCount', layero).text(teams.length);
                        } else {
                            $('#viewTeamList', layero).html('<tr><td colspan="4" style="text-align:center;">暂无数据</td></tr>');
                            $('#viewTeamCount', layero).text("0");
                        }
                    },
                    error: function() {
                        $('#viewTeamList', layero).html('<tr><td colspan="4" style="text-align:center;">加载失败</td></tr>');
                        $('#viewTeamCount', layero).text("0");
                    }
                });
            }
            
            // 获取当前排班计划ID的辅助函数
            function getCurrentSchedulingPlanId() {
                // 首先尝试从表单中获取
                var id = $('input[name="Id"]:visible').val();
                // 如果没有，尝试从弹窗中获取
                if (!id || id == "0") {
                    id = $('.layui-layer-content input[name="Id"]').val();
                }
                // 如果还是没有，使用默认值0
                return id || 0;
            }
            
            // 格式化时间函数 - 在这里定义以便全局使用
            function formatTime(timeStr) {
                if (!timeStr) return '';
                var date = new Date(timeStr);
                if (isNaN(date.getTime())) {
                    // 如果是简单的时间字符串(HH:mm)，直接返回
                    if (typeof timeStr === 'string' && timeStr.indexOf(':') > -1) {
                        return timeStr;
                    }
                    return '';
                }
                var hours = date.getHours().toString().padStart(2, '0');
                var minutes = date.getMinutes().toString().padStart(2, '0');
                return hours + ':' + minutes;
            }
            
            // 加载排班计划关联的班次到查看页面
            function loadViewSchedulingPlanShifts(schedulingPlanId, layero) {
                console.log("加载查看模式班次数据，排班计划ID:", schedulingPlanId);
                
                // 显示加载中
                $('.layui-tab-content .layui-tab-item:first-child table tbody', layero).html('<tr><td colspan="5" style="text-align:center;"><i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i> 正在加载...</td></tr>');
                
                $.ajax({
                    url: '/Classes/GetList',
                    type: 'post',
                    contentType: 'application/json',
                    data: JSON.stringify({
                        PageIndex: 1,
                        PageSize: 20,
                        SchedulingPlanId: schedulingPlanId
                    }),
                    success: function(res) {
                        console.log('查看模式班次数据返回:', res);
                        if(res.code === 0) {
                            var html = '';
                            if(res.data && res.data.length > 0) {
                                // 过滤数据，只显示当前排班计划ID的班次
                                var filteredData = res.data.filter(function(item) {
                                    console.log("班次项数据:", item);
                                    console.log("比较:", item.schedulingPlanId, schedulingPlanId);
                                    return item.schedulingPlanId == schedulingPlanId;
                                });
                                
                                console.log("查看模式过滤后班次数据条数:", filteredData.length);
                                
                                filteredData.forEach(function(item, index) {
                                    html += '<tr>';
                                    html += '<td>' + (index + 1) + '</td>';
                                    html += '<td>' + item.classesName + '</td>';
                                    // 使用安全的格式化时间函数
                                    html += '<td>' + formatTime(item.startTime) + '</td>';
                                    html += '<td>' + formatTime(item.endTime) + '</td>';
                                    html += '<td>' + (item.remark || '') + '</td>';
                                    html += '</tr>';
                                });
                            }
                            
                            if (html === '') {
                                html = '<tr><td colspan="5" style="text-align:center;">暂无班次数据</td></tr>';
                            }
                            
                            // 替换表格内容
                            $('.layui-tab-content .layui-tab-item:first-child table tbody', layero).html(html);
                            
                            // 更新计数 - 使用过滤后的数据长度
                            var filteredCount = res.data ? res.data.filter(function(item) {
                                return item.schedulingPlanId == schedulingPlanId;
                            }).length : 0;
                            
                            // 更新分页计数显示
                            $('.layui-tab-content .layui-tab-item:first-child .layui-laypage-count', layero)
                                .html('共 ' + filteredCount + ' 条');
                        } else {
                            $('.layui-tab-content .layui-tab-item:first-child table tbody', layero)
                                .html('<tr><td colspan="5" style="text-align:center;">加载失败: ' + res.msg + '</td></tr>');
                        }
                    },
                    error: function() {
                        $('.layui-tab-content .layui-tab-item:first-child table tbody', layero)
                            .html('<tr><td colspan="5" style="text-align:center;">加载失败，请检查网络连接</td></tr>');
                    }
                });
            }

            // 全选/全不选功能
            form.on('checkbox(shift-all)', function(data) {
                var checked = data.elem.checked;
                $('#shiftTable tbody input[type="checkbox"]').prop('checked', checked);
                form.render('checkbox');
            });
        });
    </script>
}
